#include <iostream>
#include <string>
#include <time.h>
#include <unistd.h>
#include "Protocol.hpp"
#include "Socket.hpp"

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n" << std::endl;
}

int main(int argc,char *argv[])
{
    // 接收ip和端口号
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //  构建套接字并连接套接字
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip,serverport);
    if(!r)
        return 1;
    
    srand(time(nullptr)^getpid());
    int cnt = 1;
    const std::string opers = "+-*/%=&^!";

    std::string inbuffer_stream;
    while (cnt <= 10)
    {
        std::cout << "===============第" << cnt << "次测试....., " << "===============" << std::endl;
        // 设置数据
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char oper = opers[rand()%opers.size()];
        Request req(x,y,oper);
        req.DebugPrint();

        // 获取运算式
        std::string package;
        req.Serialize(package);

        // 获取报文
        package = Encode(package);

        write(sockfd.Fd(),package.c_str(),package.size());

        char buffer[128];
        ssize_t n = read(sockfd.Fd(),buffer,sizeof(buffer));
        if(n > 0)
        {
            // 获取运算结果
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::cout << inbuffer_stream << std::endl;

            // 分解报文
            std::string content;
            bool r = Decode(inbuffer_stream,content);
            
            // 报文反序列化
            Response resp;
            r = resp.Deserialize(content);

            resp.DebugPrint();
        }

        std::cout << "=================================================" << std::endl;
        sleep(1);

        cnt++;
    }
    sockfd.Close();

    return 0;
}